package com.listen.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.listen.common.ConfigUtils;
import com.listen.common.DateFormatUtil;
import com.listen.common.HttpClientUtil;
/**
 * 建造师继续教育必修听课考试
 * */
public class JianZaoShiBixiu{

	private String cookie;
	private String userid;
	private String info;
	private int numBegin;
	private int numEnd;
	private String txtUserName;
	private String zyStr;
	List<String> msgList = null;
	private String urlprefix;
	private static String __viewstate="";
	private static String __viewstategenerator="C2EE9ABB";
	private static String __eventvalidation="";
	private Map<String,Object> resultMap = ConfigUtils.resultMap;
	private String[] result1;
	private String[] result2;
	private String[] result3;
	private String panduan;
	private String danxuan;
	private String duoxuan;
	private String Pwr="";
	private String Qwr="";
	private String Hwr="";
	private int flag;
	private ConcurrentHashMap<String, String>  msgMap = null;
	
	public JianZaoShiBixiu(int numBegin,int numEnd){
		this.numBegin = numBegin;
		this.numEnd = numEnd;
	}
	
	public static void main(String[] args) {
		JianZaoShiBixiu xuan = new JianZaoShiBixiu(52,53);//共57课,机电工程58课
		xuan.startListen();
	}
	
	public void startListen(){
		//完成
		String num = "642221198902204126";
		String code [] = num.split(",");
		System.out.println("开始听课：共"+code.length+"个");
		for(int i=0;i<code.length;i++){
			this.txtUserName = code[i];
			this.zyStr="D2";//1建筑工程，2市政工程，3机电工程，4矿业工程
			this.flag=2;//1只听课，2听课并考试，3只考试
			System.out.println("开始听第"+(i+1) +"/"+code.length +"个");
			toLoginPage();
		}
		System.out.println("全部听听完：共"+code.length+"个");
	}
	//处理get方式的跳转，并解析跳转后的页面
	public void toLoginPage(){
		msgMap = new ConcurrentHashMap<String,String>();
		CloseableHttpResponse response = null;
		String zy = this.zyStr.substring(1);
		String jsoupUrl = "http://139.199.171.22:8081/Login.aspx?ZY="+zy;
		this.urlprefix = "http://139.199.171.22:8081";
		try {
	        response = HttpClientUtil.getInstance().sendHttpGetResponse(jsoupUrl);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				HttpEntity entity = response.getEntity();  
				String html = EntityUtils.toString(entity);
				this.setCommonParms(html);//设置登录参数
				this.login(jsoupUrl);//执行登录操作
			}else{
				print("自动获取登录页面参数失败!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
        }
	}
	
	//登录
	public void login(String url){
		Map<String, String> maps = new HashMap<String, String>();
        maps.put("__VIEWSTATE", __viewstate); 
        maps.put("__VIEWSTATEGENERATOR", __viewstategenerator);
        maps.put("__EVENTVALIDATION",__eventvalidation); 
        maps.put("txtUserName",this.txtUserName);
        maps.put("txtPwd","888888");
        maps.put("ddlType", "2");//学员登录 
        maps.put("btnLogin", "");
        maps.put("txtLoginName", ""); 
        maps.put("txtDM", "");
        maps.put("txtFR", ""); 
        maps.put("zhjg", "");
        maps.put("zhfr", "");
        CloseableHttpResponse response = null;
        try {
        	HttpPost httpPost = new HttpPost(url);// 创建httpPost
        	httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        	httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        	response = HttpClientUtil.getInstance().sendHttpPost(maps,httpPost);
        	int state = response.getStatusLine().getStatusCode();
        	if(state == 302){
        		Header[] hearders = response.getHeaders("Set-Cookie");
        		String sessionId = hearders[0].getValue();
        		this.cookie = sessionId.substring(0, sessionId.indexOf(";") + 1);
        		String userIdCookie = hearders[1].getValue();
        		this.userid = userIdCookie.substring(0, userIdCookie.indexOf(";") + 1);
        		String infoCookies = hearders[2].getValue();
        		this.info = infoCookies.substring(0, infoCookies.indexOf(";"));
        		if(flag==3){//只考试
        			buildPaper();
        		}else if(flag==2 || flag == 1){
        			updateVidoSate();//听课，考试
        		}else{
        			print("登录成功后跳转标识异常--->flag="+flag);
        			logout();
        		}
        	}else{
        		print("登录失败!");
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//听课，修改视频状态
	public void updateVidoSate(){
		CloseableHttpResponse response = null;
		/*String urls = "";
		String rvCode = "00058";
		String rvCodeJson = "{\"RVCode\":\"" + rvCode + "\"}";
		String entityStr = "0";*/
		for(int i=numBegin;i<=numEnd;i++){
			try {
				String id2 = i < 10 ? "0000"+i : "000"+i;
				int number = (int)(50+Math.random()*(80-50+1));
				String Start = DateFormatUtil.getDateAnyMinuteBeforeStr(number);
				Start = Start.replaceAll(" ", "+").replaceAll(":", "%3a");
				String uid = this.userid.substring(userid.indexOf("=")+1, userid.length()-1);
				String cookie = this.cookie + this.userid + this.info +";checkUid="+uid+";id2="+id2+";Start="+ Start +";PC1=%u6210%u529F; PC2=%u6210%u529F; PC3=%u6210%u529F; PC4=%u6210%u529F;nowtime=2325;totaltime=2360;";
				String urls = this.urlprefix+"/EntpClass/Xtyl4.ashx?classid="+i+"&uid="+uid;
				HttpPost httpPost = new HttpPost(urls);// 创建httpPost
				httpPost.setHeader("X-Requested-With","XMLHttpRequest");
				httpPost.setHeader("Content-Type","application/json;utf-8");
				httpPost.setHeader("Accept","*/*");
				httpPost.setHeader("Cookie", cookie);
				response = HttpClientUtil.getInstance().sendHttpPost(httpPost);
				int state = response.getStatusLine().getStatusCode();
				if(state == 200){
					String message = "账号-"+this.txtUserName+" 第"+i +"个视频成功播放完";
					print(message);
				}else{
					String message = "账号-"+this.txtUserName+" 第"+i +"个视频播放失败!";
					print(message);
					break;
				}
				/*HttpPost httpPost = new HttpPost(urls);// 创建httpPost
				httpPost.setHeader("X-Requested-With","XMLHttpRequest");
				httpPost.setHeader("Content-Type","application/json;utf-8");
				httpPost.setHeader("Accept","*");
				httpPost.setHeader("Cookie", cookie);
				if(i==58){
					response = HttpClientUtil.getInstance().sendHttpPost(httpPost,rvCodeJson);
				}else{
					response = HttpClientUtil.getInstance().sendHttpPost(httpPost);
				}
				state = response.getStatusLine().getStatusCode();
				entityStr = EntityUtils.toString(response.getEntity(), "UTF-8");
				
				//System.out.println("state="+state +"   entityStr="+entityStr);
				if(i == 58){
					String message = "账号-"+this.txtUserName+" 第"+ i +"个视频" + entityStr;
					print(message);
				}else{
					if(state == 200 && Integer.parseInt(entityStr)==i){
						String message = "账号-"+this.txtUserName+" 第"+i +"个视频成功播放完";
						print(message);
					}else{
						String message = "账号-"+this.txtUserName+" 第"+i +"个视频播放失败!";
						print(message);
						break;
					}
				}*/
				Thread.sleep(3000);
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				HttpClientUtil.getInstance().closeResource(response);
			}
		}
		if(flag==2)//听课并考试
			buildPaper();
		else//只听课，听完退出登录
			logout();
			
	}
	
	//生成试卷
	public void buildPaper(){
		CloseableHttpResponse response = null;
		try {
			//第一步：生成试卷
			String path = this.urlprefix+"/TR_TestPaper.aspx?id=1";
			HttpGet httpGet = new HttpGet(path);
			//设置请求参数和cookie
			String cookie = this.cookie + this.userid + this.info;
			httpGet.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			httpGet.setHeader("Cookie",cookie);
	        //生成试卷
	        response = HttpClientUtil.getInstance().sendHttpGet(httpGet);
			int state = response.getStatusLine().getStatusCode();
			System.out.println("state="+state);
			if(state == HttpStatus.SC_OK){
				//第二步：解析HTML,获取题目id
				HttpEntity entity = response.getEntity();  
				String html = EntityUtils.toString(entity);
			    Document document = Jsoup.parse(html);
			    Element parm1 = document.getElementById("_thid");
			    this.panduan = parm1.attr("value");
			    Element parm2 = document.getElementById("Hidden1");
			    this.danxuan = parm2.attr("value");
			    Element parm3 = document.getElementById("Hidden2");
			    this.duoxuan = parm3.attr("value");
			    this.result1 = (panduan.substring(0, panduan.length()-1)).split(",");
			    this.result2 = (danxuan.substring(0, danxuan.length()-1)).split(",");
			    this.result3 = (duoxuan.substring(0, duoxuan.length()-1)).split(",");
			    //提交试卷
			    testOnline();
			}else{
				print("生成试卷失败");
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
        }
		
	}
	//提交试卷
	public void testOnline(){
		CloseableHttpResponse response = null;
		try {
			//设置答案
			this.setParmsValue();
			String cookie = this.cookie + this.userid + this.info;
	        List<NameValuePair> params = new ArrayList<NameValuePair>();  
	        params.add(new BasicNameValuePair("Pid", this.panduan));  
	        params.add(new BasicNameValuePair("Qid", this.danxuan));
	        params.add(new BasicNameValuePair("Hid",this.duoxuan));  
	        params.add(new BasicNameValuePair("Pwr",this.Pwr));  
	        params.add(new BasicNameValuePair("Qwr",this.Qwr));  
	        params.add(new BasicNameValuePair("Hwr", this.Hwr));
	        params.add(new BasicNameValuePair("AlNums", "0"));
	        
	        /*System.out.println("判断题="+panduan);
			System.out.println("单选题="+danxuan);
			System.out.println("多选题="+duoxuan);*/
			
	        //要传递的参数.  
	        String url = this.urlprefix+"/MarkTJ.aspx?" + URLEncodedUtils.format(params,"UTF-8");
			HttpGet httpGet = new HttpGet(url);
			httpGet.setHeader("Accept","*/*");
			httpGet.setHeader("X-Requested-With","XMLHttpRequest");
			httpGet.setHeader("Cookie",cookie);
	        response = HttpClientUtil.getInstance().sendHttpGet(httpGet);
	        int state = response.getStatusLine().getStatusCode();
	        if (state == HttpStatus.SC_OK) {  
                HttpEntity entity = response.getEntity();
                String resultStr = EntityUtils.toString(entity, "UTF-8");
                String score = resultStr.substring(0,resultStr.indexOf("|"));
                print("考试成功，本次考试成绩为："+score+"分");
            }else{
            	print("试卷提交失败！------->state="+state);
            }
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
        }
		//退出登录
		logout();
	}
		
	//退出登录
	public void logout(){
		HttpGet httpGet = null;
		CloseableHttpResponse response = null;
		try {
			String path = this.urlprefix+"/Public/Logout.aspx";
			httpGet = new HttpGet(path);
			String cookie = this.cookie + this.userid + this.info +"totaltime=2281; checkUid=38060; nowtime=2281";
			httpGet.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			httpGet.setHeader("Cookie", cookie);
			response = HttpClientUtil.getInstance().sendHttpGet(httpGet);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200 || state == 302){
				print("退出登录成功!");
			}else{
				print("退出登录失败!");
			}
		} catch (Exception e) {
			System.out.println("退出登录异常--->");
			e.printStackTrace();
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//设置登录三个参数
	public void setLoginParms(String httpUrl){
		CloseableHttpResponse response = null;
		try {
			HttpGet httpGet = new HttpGet(httpUrl);
			response = HttpClientUtil.getInstance().sendHttpGet(httpGet);
			int state = response.getStatusLine().getStatusCode();
			if(state==200){
				HttpEntity entity = response.getEntity();  
				String html = EntityUtils.toString(entity);
				setCommonParms(html);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
        }
	}
	
	//设置登录参数
	public void setCommonParms(String html){
		Document document = Jsoup.parse(html);
	    Element parm1 = document.getElementById("__VIEWSTATEGENERATOR");
	    __viewstategenerator = parm1.attr("value");
	    Element parm2 = document.getElementById("__EVENTVALIDATION");
	    __eventvalidation = parm2.attr("value");
	    Element parm3 = document.getElementById("__VIEWSTATE");
	    __viewstate = parm3.attr("value");
	    //System.out.println("__viewstategenerator="+__viewstategenerator);
	    //System.out.println("__eventvalidation="+__eventvalidation);
	    //System.out.println("__viewstate="+__viewstate);
	}
	
	private void print(String msg){
		msgMap.put("msg", msg);
		System.out.println(msg);
	}
	
	private void setParmsValue(){
		//设置判断题答案
		for(int i=0;i<this.result1.length;i++){
			String pid = this.result1[i];
			String panswer = (String) this.resultMap.get(pid);
			if(!"Yes".equalsIgnoreCase(panswer)&&!"No".equalsIgnoreCase(panswer)){
				panswer = "Yes";
			}
			if(i==0)
				Pwr = panswer;
			else
				Pwr = Pwr + "," + panswer;
		}
		this.Pwr = this.Pwr + ",";
		
		//设置单选题答案
		for(int i=0;i<this.result2.length;i++){
			String pid = this.result2[i];
			String panswer = (String) resultMap.get(pid);
			if(!"A".equalsIgnoreCase(panswer)&&!"B".equalsIgnoreCase(panswer)
					&&!"C".equalsIgnoreCase(panswer)&&!"D".equalsIgnoreCase(panswer)){
				panswer = "A";
			}
			if(i==0){
				Qwr = panswer;
			}else{
				Qwr = Qwr + "," + panswer;
			}
				
		}
		this.Qwr = Qwr + ",";
		//设置多选题答案
		for(int i=0;i<this.result3.length;i++){
			String pid = this.result3[i];
			String panswer = (String) resultMap.get(pid);
			if(panswer==null || panswer.trim().length()!=9){
				panswer = "A|B|C|D|0";
			}
			if(i==0)
				Hwr = panswer;
			else
				Hwr = Hwr + "," + panswer;
		}
		this.Hwr = Hwr + ",";
		/*System.out.println("Pwr="+Pwr);
		System.out.println("Qwr="+Qwr);
		System.out.println("Hwr="+Hwr);*/
	}
}
